package com.haochang.chunkvod.controller.activity.order;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseTextView;
import com.haochang.base.EventProxy;
import com.haochang.base.IEventConstant;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.VodConstant;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.database.order.BaseInfoDao;
import com.haochang.chunkvod.app.database.order.GoodsInfoDao;
import com.haochang.chunkvod.app.database.order.PartInfoDao;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.HelperUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.app.utils.VibratorUtil;
import com.haochang.chunkvod.controller.adapter.order.OrderHomePageAdapter;
import com.haochang.chunkvod.model.BaseInfo;
import com.haochang.chunkvod.model.custom.CustomDialogData;
import com.haochang.chunkvod.model.order.OrderData;
import com.haochang.chunkvod.model.order.PartInfo;
import com.haochang.chunkvod.model.order.RoomInfo;
import com.haochang.chunkvod.tools.vod.event.EventObserver;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshBase;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshGridView;
import com.haochang.chunkvod.view.vod.partition.PartLayout;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;

/**
 * @author qintao
 *         created at 2016/5/31 18:13
 *         点餐主页入口
 */

public class OrderHomePageActivity extends BaseActivity implements EventObserver
{
	private BaseTextView tv_weChatInfo;
	private TitleView titleView;
	private PartLayout tabSwitcher;
	private PullToRefreshGridView mGridView;
	private OrderHomePageAdapter adapter;
	private View img_part_modify;
	private OrderData orderData;
	private CustomDialogData customDialogData;
	private List<RoomInfo> roomInfoList = new ArrayList<RoomInfo>();//房间列表
	private List<RoomInfo> mRoomDataInfoList = new ArrayList<RoomInfo>();//有点餐数据的房间列表
	private List<PartInfo> partInfoList = new ArrayList<PartInfo>();//分区信息
	private List<BaseInfo> baseInfoList = new ArrayList<BaseInfo>();//颜色信息
	private Timer timer;
	private TimerTask timerTask;
	private boolean isShowTable = false;
	private String pId = "";
	private String sortType = "room";

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		EventProxy.addEventListener(this, IEventConstant.EVENT_DESK_ID);
	}

	@Override
	public void onResume()
	{
		super.onResume();
		if (null == timer)
			timer = new Timer();
		if (null == timerTask)
			timerTask = new TimerTask()
			{
				@Override
				public void run()
				{
					handler.sendEmptyMessage(0);
				}
			};
		timer.schedule(timerTask, 0, 10000);
	}

	Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			getRoomInfoData(pId, sortType, false);
		}
	};

	@Override
	public void receiveParam()
	{
	}

	@Override
	public void initData()
	{
		isShowTable = HelperUtils.getHelperAppInstance().getBValue("isShowTable", false);
		sortType = HelperUtils.getHelperAppInstance().getSValue("isShowSortType", "room");
		orderData = new OrderData(OrderHomePageActivity.this);
		customDialogData = new CustomDialogData(OrderHomePageActivity.this);
		setPartInfo();
	}

	private void setPartInfo()
	{
		partInfoList.clear();
		List<PartInfo> list = PartInfoDao.getDao().queryBuilderAll(PartInfo.class, isShowTable ? "is_table_select" : "is_room_select", true);
		if (!CollectionUtils.isEmpty(list))
		{
			StringBuffer sb = new StringBuffer();
			for (PartInfo partInfo : list)
			{
				sb.append(partInfo.getPart_id() + ",");
			}
			PartInfo info = new PartInfo();
			info.setPartName("全部");
			info.setPart_id(pId = sb.toString());
			partInfoList.add(info);
			partInfoList.addAll(list);
		} else
		{
			PartInfo info = new PartInfo();
			info.setPartName("全部");
			info.setPart_id(pId = "");
			partInfoList.add(info);
		}
	}

	private void setPartView()
	{
		tabSwitcher.removeAllViews();
		tabSwitcher.cleanTabView();
		if (!CollectionUtils.isEmpty(partInfoList))
		{
			for (PartInfo info : partInfoList)
			{
				tabSwitcher.addTab(info);
			}
		}
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_home_page_order);
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(R.string.order).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				finish();
				animRightToLeft();
			}

			@Override
			public void onDoneClick()
			{
				final List<String> list = new ArrayList<String>();
				if (!isShowTable)
				{
					if (!TextUtils.equals("time", sortType))
						list.add("按离场时间排序");
					else
						list.add("按房号排序");
					list.add("预结查询");
					list.add("备注查询");
				}
				list.add("外带");
				if (!isShowTable)
					list.add("消费办法");
				if (isShowTable)
					list.add("显示房间");
				else
					list.add("显示桌台");
				list.add("退出登录");
				int location[] = new int[2];
				ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
				img.getLocationOnScreen(location);
				int x = location[0];
				final VodPopWindow pop = new VodPopWindow(OrderHomePageActivity.this, list);
				pop.showPopupWindow(titleView, x);
				pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
				{
					@Override
					public void onSelectItem(int position)
					{
						String text = list.get(position);
						if (TextUtils.equals(text, "按离场时间排序"))
						{
							sortType = "time";
							HelperUtils.getHelperAppInstance().setValue("isShowSortType", sortType);
							getRoomInfoData(pId, sortType, false);
						} else if (TextUtils.equals(text, "按房号排序"))
						{
							sortType = "room";
							HelperUtils.getHelperAppInstance().setValue("isShowSortType", sortType);
							getRoomInfoData(pId, sortType, false);
						} else if (TextUtils.equals(text, "预结查询"))
						{
							Intent intent = new Intent(OrderHomePageActivity.this, ExpectedQueryListActivity.class);
							startActivity(intent);
						} else if (TextUtils.equals(text, "备注查询"))
						{
							Intent intent = new Intent(OrderHomePageActivity.this, RemarkQueryListActivity.class);
							startActivity(intent);
						} else if (TextUtils.equals(text, "消费办法"))
						{
							Intent intent = new Intent(OrderHomePageActivity.this, PhotoLookOverActivity.class);
							startActivity(intent);
						} else if (TextUtils.equals(text, "外带"))
						{
							Intent intent = new Intent(OrderHomePageActivity.this, OrderMainActivity.class);
							intent.putExtra(IntentKey.ORDER_TAKEOUT, true);
							intent.putExtra(IntentKey.ROOM_NUM, "外带");
							intent.putExtra(IntentKey.ROOM_ID, VodConstant.TAKEOUT_ROOMID);
							intent.putExtra(IntentKey.BILL_ID, VodConstant.TAKEOUT_BILLID);
							intent.putExtra(IntentKey.CHARGING_ROOM_TYPE_ID, "");
							startActivity(intent);
						} else if (TextUtils.equals(text, "显示桌台"))
						{
							isShowTable = true;
							HelperUtils.getHelperAppInstance().setValue("isShowTable", true);
							setPartInfo();
							setPartView();
							getRoomInfoData(pId, sortType, false);
						} else if (TextUtils.equals(text, "显示房间"))
						{
							isShowTable = false;
							HelperUtils.getHelperAppInstance().setValue("isShowTable", false);
							setPartInfo();
							setPartView();
							getRoomInfoData(pId, sortType, false);
						} else if (TextUtils.equals(text, "退出登录"))
						{
							loginOut();
						}
					}
				});
			}
		});

		mGridView = (PullToRefreshGridView) findViewById(R.id.app_grid);
		mGridView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
		mGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>()
		{
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView)
			{
				getRoomInfoData(pId, sortType, false);
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView)
			{

			}
		});
		adapter = new OrderHomePageAdapter(OrderHomePageActivity.this, R.layout.item_home_page_order_grid_layout, roomInfoList);
		mGridView.setAdapter(adapter);
		tv_weChatInfo = (BaseTextView) findViewById(R.id.tv_weChatInfo);
		tv_weChatInfo.setVisibility(View.GONE);
		img_part_modify = findViewById(R.id.img_part_modify);
		img_part_modify.setOnClickListener(mOnBaseClickListener);
		tabSwitcher = (PartLayout) findViewById(R.id.tabSwitcher);
		setPartView();
		tabSwitcher.setOnTabChangedListener(new PartLayout.OnTabChangedListener()
		{
			@Override
			public void onTabChanged(int last, int current, String partId)
			{
				tabSwitcher.setSelectedTable(current, partId);
				pId = partId;
				getRoomInfoData(partId, sortType, false);
			}
		});
		getRoomInfoData(pId, sortType, true);
	}

	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.img_part_modify:
				Intent intent = new Intent(OrderHomePageActivity.this, PartModifyActivity.class);
				intent.putExtra(IntentKey.ROOM_TABLE_TYPE, isShowTable ? PartModifyActivity.RoomTypeEnum.TABLE : PartModifyActivity.RoomTypeEnum.ROOM);
				startActivityForResult(intent, IntentCode.PART_DATA_REQUEST);
				break;
			case R.id.tv_weChatInfo:
				onOrderWeChatClick();
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 获取房间信息或者桌台数据
	 *
	 * @param area_id  区域id
	 * @param sortType 排序方式
	 */
	public void getRoomInfoData(String area_id, String sortType, boolean isLoading)
	{
		mRoomDataInfoList = GoodsInfoDao.getDao().queryGoodInfosByBillId();
		baseInfoList = BaseInfoDao.getDao().queryBuilderAll(BaseInfo.class, "is_room", !isShowTable);
		orderData.requestRoomStatus(area_id, sortType, isLoading, isShowTable, new OrderData.IRoomStatusListener()
		{
			@Override
			public void onRequestSuccess(int task_order_count, List<RoomInfo> list, boolean clear)
			{
				if (adapter != null)
					adapter.clearAllAnimation();
				if (task_order_count > 0)
				{
					tv_weChatInfo.setVisibility(View.VISIBLE);
					tv_weChatInfo.setText(String.format("有%d个待确认的微信点餐", task_order_count));
					tv_weChatInfo.setOnClickListener(mOnBaseClickListener);
				}
				if (!CollectionUtils.isEmpty(list))
				{
					if (clear)
						roomInfoList.clear();
					roomInfoList.addAll(list);
					if (!CollectionUtils.isEmpty(mRoomDataInfoList))
					{
						for (int i = 0; i < mRoomDataInfoList.size(); i++)
						{
							RoomInfo dbInfo = mRoomDataInfoList.get(i);
							for (int j = 0; j < roomInfoList.size(); j++)
							{
								RoomInfo info = roomInfoList.get(j);
								if (TextUtils.equals(dbInfo.getBillId(), info.getBillId()))
								{
									info.setOrderNum(dbInfo.getOrderNum());
									break;
								}
							}
						}
					}
				} else
				{
					roomInfoList.clear();
					if (!isShowTable)
						ToastUtils.showText(context, "此分区暂时没有房间");
					else
						ToastUtils.showText(context, "此分区暂时没有桌台");
				}
				adapter.setBaseInfoList(baseInfoList);
				adapter.replaceAll(roomInfoList);
				if (isOpenVibrator(roomInfoList))
					VibratorUtil.getInstance().startVibrate(OrderHomePageActivity.this, true);
				else
					VibratorUtil.getInstance().stopVibrate();
			}

			@Override
			public void onFinish()
			{
				if (mGridView != null && mGridView.isRefreshing())
					mGridView.onRefreshComplete();
			}
		});
	}

	/**
	 * 点击微信点餐确认
	 */
	private void onOrderWeChatClick()
	{
		Intent intent = new Intent(OrderHomePageActivity.this, OrderWeChatListActivity.class);
		startActivity(intent);
	}

	/**
	 * 是否开启震动服务的判断
	 */
	private boolean isOpenVibrator(List<RoomInfo> list)
	{
		if (CollectionUtils.isEmpty(list))
			return false;
		boolean flag = false;
		for (int i = 0; i < list.size(); i++)
		{
			RoomInfo roomInfo = list.get(i);
			if (roomInfo.isFlick())
			{
				flag = true;
				break;
			}
		}
		return flag;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == IntentCode.PART_DATA_REQUEST && resultCode == RESULT_OK && data != null)
		{
			ArrayList<PartInfo> selectPartList = data.getParcelableArrayListExtra(IntentKey.PART_DATA);
			tabSwitcher.removeAllViews();
			tabSwitcher.cleanTabView();
			tabSwitcher.setVisibility(View.VISIBLE);
			PartInfo info = new PartInfo();
			info.setPartName("全部");
			if (CollectionUtils.isEmpty(selectPartList))
			{
				info.setPart_id("");
				tabSwitcher.addTab(info);
			} else
			{
				StringBuffer sb = new StringBuffer();
				for (PartInfo partInfo : selectPartList)
				{
					sb.append(partInfo.getPart_id() + ",");
				}
				info.setPart_id(sb.toString());
				tabSwitcher.addTab(info);
				for (PartInfo partInfo : selectPartList)
				{
					tabSwitcher.addTab(partInfo);
				}
			}
			tabSwitcher.setSelectedTable(0, info.getPart_id());
			pId = info.getPart_id();
			getRoomInfoData(info.getPart_id(), sortType, false);
		} else if (requestCode == IntentCode.ROOM_REMARK_REQUEST && resultCode == RESULT_OK && data != null)
		{
			String billId = data.getStringExtra(IntentKey.BILL_ID);
			String remark = data.getStringExtra(IntentKey.REMARK);
			for (RoomInfo roomInfo : roomInfoList)
			{
				if (billId.equals(roomInfo.getBillId()))
				{
					roomInfo.setRoomRemark(remark);
					break;
				}
			}
			adapter.notifyDataSetChanged();
		} else if (requestCode == IntentCode.ROOM_PEOPLE_REQUEST && resultCode == RESULT_OK && data != null)
		{
			final String billId = data.getStringExtra(IntentKey.BILL_ID);
			final String amount = data.getStringExtra(IntentKey.CUSTOM_DIALOG_CONTENT);
			customDialogData.requestModifyRoomPeoPleNum(billId, amount, new CustomDialogData.IRoomPeopleListener()
			{
				@Override
				public void onRequestSuccess()
				{
					for (RoomInfo roomInfo : roomInfoList)
					{
						if (billId.equals(roomInfo.getBillId()))
						{
							roomInfo.setRoomPeopleCount(Integer.parseInt(amount));
							break;
						}
					}
					adapter.notifyDataSetChanged();
				}
			});
		}
	}

	private void cancelTask()
	{
		if (timer != null)
		{
			timer.cancel();
			timer = null;
		}
		if (timerTask != null)
		{
			timerTask.cancel();
			timerTask = null;
		}
	}

	@Override
	public void onPause()
	{
		super.onPause();
		cancelTask();
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		EventProxy.removeEventListener(IEventConstant.EVENT_DESK_ID, this);
		cancelTask();
	}

	@Override
	public void onNotify(Object sender, int eventId, Object... args)
	{
		switch (eventId)
		{
		case IEventConstant.EVENT_DESK_ID:
			String bill_id = (String) args[0];
			String room_id = (String) args[1];
			for (int i = 0; i < roomInfoList.size(); i++)
			{
				RoomInfo roomInfo = roomInfoList.get(i);
				if (TextUtils.equals(room_id, roomInfo.getRoomId()))
				{
					roomInfo.setBillId(bill_id);
					break;
				}
			}
			break;
		default:
			break;
		}
	}
}
